<template>
  <div>
    <AModal
      v-bind="$attrs"
      width="800px"
      :body-style="{ padding: '0px' }"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AAlert>需要注意一下采购单与出入库存的数据</AAlert>
      <div style="overflow: auto; padding: 20px">
        <AForm ref="formRef" :model="form" auto-label-width>
          <ARow :gutter="10">
            <ACol :span="12">
              <AFormItem
                field="materialStockId"
                label="产品"
                :rules="[{ required: true, message: '请选择产品' }]"
                :validate-trigger="['change', 'blur']"
              >
                <ASelect
                  v-model="form.materialStockId"
                  v-model:input-value="productSearch"
                  allow-search
                  placeholder="请选择产品名称"
                  :trigger-props="{ contentStyle: { width: 'max-content' } }"
                  :filter-option="proFilter"
                  @change="changeEvent('material')"
                >
                  <template #empty>
                    <div style="padding: 6px 12px">
                      <ALink :hoverable="false" @click="openAdd()"> 新增其它 </ALink>
                    </div>
                  </template>
                  <AOption
                    v-for="(item, index) in stockList"
                    :key="index"
                    :label="item.materialName"
                    :value="`${item.materialStockId}-${item.spec}`"
                  >
                    <div class="w100 erp-row-center-between">
                      <div>{{ item.materialName }}</div>
                      <ATag v-if="item.spec" color="blue">
                        {{ item.spec }}
                      </ATag>
                    </div>
                  </AOption>
                </ASelect>
              </AFormItem>
            </ACol>
            <ACol :span="6">
              <AFormItem field="spec" label="规格">
                {{ form.spec }}
              </AFormItem>
            </ACol>
            <ACol :span="6">
              <AFormItem field="unit" label="单位">
                {{ form.unit }}
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="materialCategory" label="类别">
                {{ form.materialCategory }}
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="inboundQty" label="入库数量">
                <AInputNumber
                  v-model="form.inboundQty"
                  model-event="input"
                  placeholder="请输入入库数量"
                />
              </AFormItem>
            </ACol>
            <!-- <ACol>
            <AFormItem field="remrk" label="备注">
              <ATextarea v-model="form.remark" />
            </AFormItem>
          </ACol> -->
          </ARow>
        </AForm>
      </div>
    </AModal>
    <addStock
      v-model:visible="addProductVisible"
      title="新增其它"
      :check-data="{ materialName: productSearch }"
      @reload="getProductList"
    ></addStock>
  </div>
</template>

<script lang="ts" setup>
import { Message, SelectOptionData } from '@arco-design/web-vue'
import addStock from '@renderer/views/warehouseManage/Inventory/other/editPopupForm.vue'
import { getSupplierAllList, SupplierResItem } from '@renderer/api/company'
import {
  editStockRecord,
  getStockAllList,
  getStockRecordDetail,
  StockRecordReq,
  StockRecordResItem,
  StockResItem
} from '@renderer/api/warehouseManage'
import { useMenuState } from '@renderer/store'
import { deleteNullObject } from '@renderer/utils/data-processing'

interface Props {
  [key: string]: any
  checkData?: Partial<StockRecordResItem>
}
const props = withDefaults(defineProps<Props>(), {
  checkData: () => {
    return {}
  }
})
const emit = defineEmits(['update:visible', 'reload'])
const attrs = useAttrs()
const formRef = ref()
const form = ref<StockRecordReq>({
  supplierId: '',
  materialStockId: '',
  orderCode: '',
  remark: '',
  formType: 0,
  inboundQty: 0,
  outboundQty: 0,
  stockRecordId: '',
  recordType: 0,
  materialName: '',
  materialCategory: '',
  spec: '',
  materialCode: '',
  materialDesc: '',
  fluteType: '',
  boxSpec: '',
  crimpLine: '',
  unit: '',
  storageArea: '',
  materialType: 3,
  stockQty: 0,
  unitPrice: 0,
  outStockQty: 0,
  recordId: ''
})
const supplierList = ref<SupplierResItem[]>([])
const menuParam = useMenuState()
const productSearch = ref('')
const addProductVisible = ref(false)

// 获取供应商列表
const getCompanyList = () => {
  getSupplierAllList({ supplierName: '' }).then((res) => {
    supplierList.value = res.data.list
  })
}
const stockList = ref<StockResItem[]>([])
// 获取产品列表
const getProductList = () => {
  getStockAllList({ materialName: '', materialType: 3 }).then((res) => {
    stockList.value = res.data.list
  })
}
// 获取详情
const getDetail = () => {
  getStockRecordDetail({ stockRecordId: props.checkData.stockRecordId! }).then((res) => {
    form.value = res.data
    form.value.materialStockId = `${form.value.materialStockId}-${form.value.spec}`
  })
}

// 弹窗事件
const modalEvent = (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate((errors: any) => {
        if (!errors) {
          // 新增
          if (['新增', '复制'].includes(attrs.title as string)) {
            form.value.stockRecordId = undefined
          }
          form.value.formType = 0
          form.value.materialType = 3
          form.value.materialStockId = form.value.materialStockId?.split('-')[0]
          editStockRecord(deleteNullObject(form.value)).then(() => {
            Message.success(
              ['新增', '复制'].includes(attrs.title as string) ? '新增成功' : '修改成功'
            )
            modalEvent('cancel')
            emit('reload')
          })
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      emit('update:visible', false)
      break
    case 'open':
      menuParam.switchEditStatus(true)
      getCompanyList()
      getProductList()
      if (['修改', '复制'].includes(attrs.title as string)) {
        getDetail()
      }
      break
    case 'cancel':
      formRef.value.resetFields()
      menuParam.switchEditStatus(false)
      emit('update:visible', false)
      break

    default:
      break
  }
}

// 新增其它
const openAdd = () => {
  addProductVisible.value = true
}

const changeEvent = (type: string) => {
  switch (type) {
    case 'material':
      {
        const temp = stockList.value.find(
          (item) => `${item.materialStockId}-${item.spec}` === form.value.materialStockId
        )
        if (temp) {
          form.value.materialCategory = temp.materialCategory
          form.value.spec = temp.spec
          form.value.unit = temp.unit
        }
      }
      break

    default:
      break
  }
}
const proFilter = (inputValue: string, option: SelectOptionData) => {
  return (
    (option.value as string)?.split('-')[1].includes(inputValue) ||
    option.label?.includes(inputValue)
  )
}
</script>
<style scoped lang="less">
:deep(.arco-select-option-content) {
  width: 100%;
}
</style>
